package com.zam.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.zam.comment.Constants;
import com.zam.exception.ServiceException;
import com.zam.pojo.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.zam.comment.Constants.USER_NEWS_KEY;
import static com.zam.comment.Constants.USER_TOKEN_TIME;

/**
 * @Author talent_dog
 * @Date 2023/12/15 17:49
 * @Version 1.0
 */
@Configuration
public class TokenIterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public TokenIterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); //获取请求头中的token,前端必须放在请求头中
        //如果不映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.CODE_401, "未登陆，请重新登录");
        }
        //从token中获取userId
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constants.CODE_401, "token验证失败");
        }

        //从redis中查询用户
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(USER_NEWS_KEY + userId);
        if (entries.size()==0) {
            throw new ServiceException(Constants.CODE_401, "登陆超时，请重新登录");
        }
        stringRedisTemplate.expire(USER_NEWS_KEY + userId,USER_TOKEN_TIME, TimeUnit.MINUTES);
        User user = BeanUtil.fillBeanWithMap(entries, new User(), true);

        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录");
        }
        return true;
    }

}
